<?php

/* Configuration */
	$user = 'pgriesefox';
	
/* End of configuration - nothing to change below this line */
	
class fmFolder
{
	  public $nid;
	  public $name;
//	  public $folders = array();
	  public $items = array();
}

class fmItem
{
	public $nid;
	public $name;
	public $url;
}

function readFileContents($filename)
{
	$handle = fopen ($filename, "r");
	$contents = fread ($handle, filesize ($filename));
	fclose ($handle);

	return $contents;
}

function addObject(&$root, $type, $pnid, $nid, $name, $url='')
{
	$success = false;
	
	// check is $root is a folder, otherweise return false
	if (get_class($root) <> 'fmFolder') return $success;
	
	if ($root->nid == $pnid)
	{
		if ($type=='folder')
		{
			$folder = new fmFolder;
			$folder->name=$name;
			$folder->nid=$nid;
			
			array_push($root->items, $folder);
			
		}
		elseif($type=='bookmark')
		{
			$bookmark = new fmItem;
			$bookmark->nid=$nid;
			$bookmark->name=$name;
			$bookmark->url=$url;

			array_push($root->items, $bookmark);
		}
		
		$success=TRUE;
	}
	else
	{	
		// set array cursor to first element
		reset($root->items);
		
		do
		{
			addObject(current($root->items), $type, $pnid, $nid, $name, $url);
		} while (next($root->items) && ($success==FALSE));
	}

	return $success;
	
}

function parseCommands($commands)
{
	$root = new fmFolder;
	$root->nid='ROOT';
	
	foreach ($commands as $command)
	{
		if ($command->action == 'insert')
		{
			if ($command->nid == 'ROOT')
			{
				$root->name=$command->args->name;
			}
			else
			{
				addObject($root, $command->args->ntype, $command->args->pnid, $command->nid, $command->args->name, $command->args->url);
			}
		}
	}
	
	return $root;
}

function renderHtmlTree($tree, $depth)
{
	$html .= '<div class="folder">'.$tree->name;
	
	reset($tree->items);
	do
	{
		$item = current($tree->items);
		
		if (get_class($item)=='fmFolder')
		{
			$html .= renderHtmlTree($item, $depth+1);
		}
		elseif (get_class($item)=='fmItem')
		{
			$html .= '<div class="item"><a href="'.$item->url.'">'.$item->name.'</a></div>';
		}
		
	} while (next($tree->items));
	
	$html .= '</div>';
	
	return $html;
}
	
function processFoxmarks()
{
	// Read file contents
	$contents = readFileContents($GLOBALS['user']);

	// decode JSON serialization
	$obj = json_decode($contents);
	$commands = $obj->commands;
	
	// generate bookmark tree
	$tree = parseCommands($commands);

	return renderHtmlTree($tree, 1);
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" lang="de">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link type="text/css" rel="stylesheet" href="style.css" />
</head><body><?=processFoxmarks(); ?></body></html>
